package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedida.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper articleMapper;

    /**
     * 计算文章的分值
     */
    @Override
    public void computeHotArticle() {
        //1.查询前五天文章数据
        Date date = DateTime.now().minusDays(5).toDate();

        List<ApArticle> list = articleMapper.findArticleListLast5Days(date);
        //2.计算分值
        List<HotArticleVo> hotArticleVoList = computeScore(list);
        //3.缓存到redis中
        cacheTagToRedis(hotArticleVoList);
    }


    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 缓存到redis中
     *
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //每个频道缓存30条分值较高的文章数据
        ResponseResult responseResult = wemediaClient.findList();
        if (responseResult.getCode() == 200) {
            String jsonString = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSON.parseArray(jsonString, WmChannel.class);
            for (WmChannel wmChannel : wmChannels) {
                List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                        .filter(x -> x.getChannelId().equals(wmChannel.getId()))
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                        .limit(30)
                        .collect(Collectors.toList());
                //缓存到redis中
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId(),
                        JSON.toJSONString(hotArticleVos));
            }

        }
        //缓存推荐数据
        List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG,
                JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算分值
     *
     * @param list
     * @return
     */
    private List<HotArticleVo> computeScore(List<ApArticle> list) {
        int sum = 0;
        List<HotArticleVo> ret = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            for (ApArticle apArticle : list) {
                HotArticleVo hot = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hot);
//计算分值
                if (apArticle.getLikes() != null)
                    sum += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
                if (apArticle.getCollection() != null)
                    sum += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
                if (apArticle.getComment() != null)
                    sum += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
                if (apArticle.getViews() != null)
                    sum += apArticle.getViews();
                hot.setScore(sum);
                ret.add(hot);
            }
        }
        return ret;
    }
}

